package com.softserveinc.cheatsheet.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.softserveinc.cheatsheet.dao.UserAccountDao;
import com.softserveinc.cheatsheet.entity.UserAccount;
import com.softserveinc.cheatsheet.entity.UserAuthority;

@Repository
public class JpaUserAccountDaoImpl implements UserAccountDao {

	
	@PersistenceContext(type=PersistenceContextType.EXTENDED)
	private EntityManager entityManager;

	public JpaUserAccountDaoImpl() {
	}

	public JpaUserAccountDaoImpl(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

    @Transactional
	public void create(UserAccount account) {
		entityManager.persist(account);
	}

    @Transactional
	public void create(UserAuthority userAuthority) {
		entityManager.persist(userAuthority);
	}

    @Transactional
    public List<UserAccount> list() {
		return entityManager.createNamedQuery(
				UserAccount.LIST_USER_ACCOUNT_BY_NAME_QUERY, UserAccount.class)
				.getResultList();
	}
    
    @Transactional
	public UserAccount read(Long id) {
		return entityManager.find(UserAccount.class, id);
	}

    @Transactional
    public UserAccount read(String accountName) {
		return entityManager
				.createNamedQuery(UserAccount.GET_USER_ACCOUNT_BY_NAME_QUERY,
						UserAccount.class).setParameter("name", accountName)
				.getSingleResult();
	}

    @Transactional
    public UserAuthority readUserRole(String roleName) {
		return entityManager
				.createNamedQuery(UserAuthority.GET_AUTHORITY_BY_NAME_QUERY,
						UserAuthority.class).setParameter("name", roleName)
				.getSingleResult();
	}

    @Transactional
    public void update(UserAccount account) {
		if (account != null) {
			entityManager.merge(account);
		}
	}

    @Transactional
    public void delete(UserAccount account) {
		if (account != null) {
			entityManager.remove(account);
		}
	}

    @Transactional
    public void delete(Long id) {
		UserAccount userAccount = read(id);
		if (userAccount != null) {
			entityManager.remove(userAccount);
		}
	}


}
